/*
 * comlan
 */

package com.promfy.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.util.Log;

/**
 * implement tcp/udp connection
 * @author mfy
 *
 */
public class TcpUdpUtil {
	
	/**
	 * send message by tcp
	 * tcp是面向连接的,所以有返回值
	 * @param url
	 * @param port
	 * @param message
	 */
	public static void tcpSend(String url, int port, String message) {
		OutputStream out = null;
		InputStreamReader input = null;
		BufferedReader inBuff = null;
		PrintWriter output = null;
		Socket s = null;
		try {
			//1.create tcp connect
			s = new Socket(url, port);
			//2.send message by outputStream
			out = s.getOutputStream();
			output = new PrintWriter(out, true);//param "true" means auto flush, otherwise you should out.flush().
			output.println(message);
			//3.read message by inputStream from server.
			input = new InputStreamReader(s.getInputStream());
			inBuff = new BufferedReader(input);
			String result = inBuff.readLine();
			Log.d("test", "message From Server:" + result);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inBuff != null) {
				try {
					inBuff.close();
				} catch (IOException e) {
					e.printStackTrace();
					inBuff = null;
				}
			}
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
					input = null;
				}
			}
			if (output != null) {
				try {
					output.close();
				} catch (Exception e) {
					e.printStackTrace();
					output = null;
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					out = null;
				}
			}
			if (s != null) {
				try {
					s.close();
				} catch (IOException e) {
					e.printStackTrace();
					s = null;
				}
			}
		}
	}
	
	public static void tcpServer(int port){
		ServerSocket ss = null;
		PrintWriter output = null;
		BufferedReader inBuff = null;
		InputStreamReader input = null;
		Socket s = null;
		try {  
            Boolean endFlag = false;  
            //1.create tcp server connect.
            ss = new ServerSocket(port); 
            //2.loop to receiver tcp request. 
            while (!endFlag) {  
            	//2.1.accept tcp request.
                s = ss.accept(); 
                //2.2.get message from inputStream.
                input = new InputStreamReader(s.getInputStream());
                inBuff = new BufferedReader(input);
                //.response message from outStream.
                output = new PrintWriter(s.getOutputStream(),true);  
                String message = inBuff.readLine();  
                Log.d("Tcp Demo", "message from Client:" + message);  
//                Log.d("Tcp Demo", "message from Client:" + new String(message.getBytes("ISO_8859_1"),"ISO_8859_1"));  
                //Log.d("Tcp Demo", "message1 from Client:"+new String(message.getBytes("gbk")));  
               // Log.d("Tcp Demo", "message1 from Client:"+new String(message.getBytes("gbk")),"gbk");  
                output.println("message received!");  
                if("shutDown".equals(message)){  
                    endFlag=true;  
                }  
                s.close();  
            }  
   
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally{
        	if (output != null) {
        		try {
        			output.close();
        		} catch (Exception e) {
        			e.printStackTrace();
        			output = null;
        		}
        	}
        	if (inBuff != null) {
				try {
					inBuff.close();
				} catch (IOException e) {
					e.printStackTrace();
					inBuff = null;
				}
			}
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
					input = null;
				}
			}
			if (s != null && !s.isClosed()) {
				try {
					s.close();
				} catch (IOException e) {
					e.printStackTrace();
					s = null;
				}
			}
			if (ss != null) {
				try {
					ss.close();
				} catch (IOException e) {
					e.printStackTrace();
					ss = null;
				}
			}
        }
	}
	
	
	/**
	 * send message by udp.
	 * udp不是面向连接的,只发送消息,无返回.
	 * @param url
	 * @param port
	 * @param message
	 */
	public static void udpSend(String url, int port, String message) {  
		message = (message == null ? "Hello IdeasAndroid!" : message);
		DatagramSocket s = null;
		DatagramPacket p = null;
		try {
			//1.create udp connect.
			s = new DatagramSocket();
			//2.create udp package.
			InetAddress local = null;
			local = InetAddress.getByName(url); //change ip to server ip.
			int msgLength = message.length();
			byte[] messageByte = message.getBytes();
			p = new DatagramPacket(messageByte, msgLength, local, port);
			s.send(p);
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			if(s != null){
				s.close();
			}
		}
    } 
	
	public static void udpServer(int port){  
        byte[] message = new byte[1024];  // size of udpPacket < message.length
        try {  
            //1. create udp connect.
            DatagramSocket datagramSocket = new DatagramSocket(port);  
            //2. create udp packet.
            DatagramPacket datagramPacket = new DatagramPacket(message,message.length);  
            try {  
            	//3.loop to receiver udp packet.
                while (true) {  
                    
                    datagramSocket.receive(datagramPacket);  
                    Log.d("UDP Demo", datagramPacket.getAddress()  
                            .getHostAddress().toString()  
                            + ":" + new String(datagramPacket.getData(), 0,datagramPacket.getLength()));  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        } catch (SocketException e) {  
            e.printStackTrace();  
        } 
	}
	
}
